//
// Created by zhupi on 2024/9/29.
//

#ifndef DEMO2_TREE_BASE_MODEL_H
#define DEMO2_TREE_BASE_MODEL_H

#include "tree_base_common.h"
#include "tree_item_icon_ctrl.h"
#include <QAbstractItemModel>
#include <QBrush>
#include <QFont>

class TreeNode {
public:
    TreeStruct data_;              // 存储节点数据
    QList<TreeNode*> children_;    // 子节点列表
    TreeNode* parent_ {nullptr};   // 父节点
    QFont customFont_;          // 字体
    QColor textColor_ ;         // 字体颜色
    bool isDisabled_ {false};    // 是否显示
    TreeNode(const TreeStruct& data, TreeNode* parent = nullptr)
            : data_(data), parent_(parent) {}

    void addChild(TreeNode* child) {
        children_.append(child);
    }

    void removeChild(TreeNode* child) {
        children_.removeAll(child);
    }

    int childCount() const {
        return children_.size();
    }

    TreeNode* child(int row) const {
        return children_.value(row);
    }

    int row() const {
        if (parent_ != nullptr) {
            return parent_->children_.indexOf(const_cast<TreeNode*>(this));
        }
        return 0;
    }
};


class TreeModel : public QAbstractItemModel {
    Q_OBJECT
public:
    TreeModel(QObject* parent = nullptr)
            : QAbstractItemModel(parent) {
        rootNode_ = new TreeNode(TreeStruct()); // 创建根节点
    }

    ~TreeModel() {
        delete rootNode_;
    }

    QModelIndex index(int row, int column, const QModelIndex& parent) const override {
        if (!hasIndex(row, column, parent))
            return QModelIndex();

        TreeNode* parentNode;

        if (!parent.isValid())
            parentNode = rootNode_;
        else
            parentNode = static_cast<TreeNode*>(parent.internalPointer());

        TreeNode* childNode = parentNode->child(row);
        if (childNode)
            return createIndex(row, column, childNode);
        return QModelIndex();
    }

    QModelIndex parent(const QModelIndex& index) const override {
        if (!index.isValid())
            return QModelIndex();

        TreeNode* childNode = static_cast<TreeNode*>(index.internalPointer());
        TreeNode* parentNode = childNode->parent_;

        if (parentNode == rootNode_)
            return QModelIndex();

        return createIndex(parentNode->row(), 0, parentNode);
    }

    int rowCount(const QModelIndex& parent = QModelIndex()) const override {
        TreeNode* parentNode;
        if (!parent.isValid())
            parentNode = rootNode_;
        else
            parentNode = static_cast<TreeNode*>(parent.internalPointer());

        return parentNode->childCount();
    }

    int columnCount(const QModelIndex& parent = QModelIndex()) const override {
        return 1; // 简化为单列
    }

    QVariant data(const QModelIndex& index, int role) const override {
        if (!index.isValid()) {
            return QVariant();
        }

        TreeNode* node = static_cast<TreeNode*>(index.internalPointer());
        if (node == nullptr) {
            return QVariant();
        }

        // 设置显示的图标
        if (role == Qt::DecorationRole) {
            std::string type = node->data_.type_;
            QIcon icon;
            if (TreeItemIconCtrl::GetIns().GetIcon(type, icon)) {
                return icon; // 返回你想要的图标
            }
        }

        // 设置显示的内容
        if (role == Qt::DisplayRole) {
            return QString::fromStdString(node->data_.name_);
        }

        // 设置节点是否禁用
        if (role == Qt::ForegroundRole && node->isDisabled_) {
            return QBrush(Qt::gray); // 如果节点被禁用，字体颜色变灰
        }

        // 设置自定义颜色
        if (role == Qt::ForegroundRole) {
            return QBrush(node->textColor_);
        }

        // 设置自定义字体
        if (role == Qt::FontRole) {
            return node->customFont_;
        }

        return QVariant();
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role)
    {
        if (!index.isValid())
            return false;

        TreeNode* node = static_cast<TreeNode*>(index.internalPointer());
        if (node == nullptr)
            return false;

        // 根据角色设置数据
        if (role == Qt::EditRole) {
            node->data_.name_ = value.toString().toStdString();
            emit dataChanged(index, index);
            return true;
        }

        return false;
    }

    Qt::ItemFlags flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return Qt::NoItemFlags;

        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
    }


    // 添加树节点
    void AddTree(TreeStruct tree) {
        TreeNode* newNode;

        // 如果该节点的父节点尚未存在，先挂到根节点并存入 pendingChildren_
        if (tree.parentId_ != 0 && !nodeMap_.contains(tree.parentId_)) {
            newNode = new TreeNode(tree, rootNode_);
            rootNode_->addChild(newNode);
            pendingChildren_[tree.parentId_].append(newNode);
            nodeMap_.insert(tree.id_, newNode);

            // 通知视图更新
            QModelIndex rootIndex = createIndex(rootNode_->row(), 0, rootNode_);
            int childCount = rootNode_->childCount() - 1;
            beginInsertRows(rootIndex, childCount, childCount);
            endInsertRows();
        } else {
            // 父节点存在，正常挂载
            TreeNode* parentNode = nodeMap_.value(tree.parentId_, rootNode_);
            newNode = new TreeNode(tree, parentNode);
            parentNode->addChild(newNode);
            nodeMap_.insert(tree.id_, newNode);

            // 通知视图更新
            QModelIndex parentIndex = createIndex(parentNode->row(), 0, parentNode);
            int childCount = parentNode->childCount() - 1;
            beginInsertRows(parentIndex, childCount, childCount);
            endInsertRows();
        }

        // 检查是否有挂在根节点下等待此节点作为父节点的子节点
        if (pendingChildren_.contains(tree.id_)) {
            for (TreeNode* child : pendingChildren_.value(tree.id_)) {
                rootNode_->removeChild(child);
                newNode->addChild(child);
                child->parent_ = newNode;
            }
            pendingChildren_.remove(tree.id_);
        }

        // 遍历现有节点，检查是否有节点的父节点是新插入的节点
        QList<TreeNode*> toReparent;
        for (auto& nodePair : nodeMap_) {
            TreeNode* node = nodePair;
            if (node->data_.parentId_ == tree.id_) {
                toReparent.append(node);
            }
        }

        // 将找到的子节点重新挂载到新插入的父节点下
        for (TreeNode* child : toReparent) {
            TreeNode* oldParent = child->parent_;
            oldParent->removeChild(child);
            newNode->addChild(child);
            child->parent_ = newNode;

            // 更新视图
            QModelIndex oldParentIndex = createIndex(oldParent->row(), 0, oldParent);
            int row = oldParent->children_.indexOf(child);
            beginRemoveRows(oldParentIndex, row, row);
            endRemoveRows();

            QModelIndex newParentIndex = createIndex(newNode->row(), 0, newNode);
            int newRow = newNode->childCount() - 1;
            beginInsertRows(newParentIndex, newRow, newRow);
            endInsertRows();
        }
    }

    // 移除树节点
    void MoveItem(int id) {
        TreeNode* nodeToRemove = findNodeById(rootNode_, id);
        if (!nodeToRemove)
            return;

        TreeNode* parentNode = nodeToRemove->parent_;
        int row = nodeToRemove->row();

        beginRemoveRows(createIndex(parentNode->row(), 0, parentNode), row, row);
        parentNode->removeChild(nodeToRemove);
        delete nodeToRemove;
        endRemoveRows();
    }

    // 添加接口以禁用节点
    void SetItemDisabled(int id, bool disabled) {
        TreeNode* node = findNodeById(rootNode_, id);
        if (node) {
            node->isDisabled_ = disabled;

            // 通知视图数据已更改
            QModelIndex index = createIndex(node->row(), 0, node);
            emit dataChanged(index, index, {Qt::ForegroundRole});
        }
    }

    // 添加接口以设置字体和颜色
    void SetItemFontAndColor(int id, const QFont& font, const QColor& color) {
        TreeNode* node = findNodeById(rootNode_, id);
        if (node) {
            node->customFont_ = font;
            node->textColor_ = color;

            // 通知视图数据已更改
            QModelIndex index = createIndex(node->row(), 0, node);
            emit dataChanged(index, index, {Qt::FontRole, Qt::ForegroundRole});
        }
    }

    void MoveToParent(int nodeId, int newParentId) {
        TreeNode* node = nodeMap_.value(nodeId, nullptr);
        TreeNode* newParent = nodeMap_.value(newParentId, nullptr);

        if (!node || !newParent || node == newParent)
            return;

        TreeNode* oldParent = node->parent_;
        int row = node->row();

        // 从原父节点中移除
        beginRemoveRows(createIndex(oldParent->row(), 0, oldParent), row, row);
        oldParent->removeChild(node);
        endRemoveRows();

        // 添加到新父节点
        newParent->addChild(node);
        node->parent_ = newParent;

        QModelIndex newParentIndex = createIndex(newParent->row(), 0, newParent);
        int newRow = newParent->childCount() - 1;
        beginInsertRows(newParentIndex, newRow, newRow);
        endInsertRows();
    }

signals:
            void nodeClicked(int id);

private:
    TreeNode* rootNode_; // 根节点
    QMap<int, TreeNode*> nodeMap_; // 存储节点id和指针的映射
    QMap<int, QList<TreeNode*>> pendingChildren_; // 等待挂载的子节点
    // 递归查找节点
    TreeNode* findNodeById(TreeNode* node, int id) {
        if (node->data_.id_ == id)
            return node;

        for (TreeNode* child : node->children_) {
            TreeNode* result = findNodeById(child, id);
            if (result)
                return result;
        }

        return nullptr;
    }
};



#endif //DEMO2_TREE_BASE_MODEL_H
